package com.yfyszk.kingbird.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.yfyszk.kingbird.common.constants.Constants;
import com.yfyszk.kingbird.config.properties.IgnoreWhiteProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;
import java.util.Map;

/** 全局过滤器
 * @ClassName AuthFilter
 * @Description: TODO
 * @Author wgc
 * @Date 2020/12/17 17:38
 * @Version V1.0
 **/
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private IgnoreWhiteProperties ignoreWhiteProperties;
    /** 处理过滤器业务逻辑
     * @author wgc
     *@date 2020/12/28 0028 14:28
     * @param exchange
     * @param chain
     * @return reactor.core.publisher.Mono<java.lang.Void>
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        List<String> ignoreList = ignoreWhiteProperties.getWhites();
        String url_ = exchange.getRequest().getURI().getPath();
        log.info("请求的url:{}", url_);
        //RequestPath path = exchange.getRequest().getPath();
       // log.info("请求的path:{}", path);
       // URI url = (URI) exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
        if (!CollectionUtils.isEmpty(ignoreList)) {
            if (ignoreList.contains(url_.toString())) {
                return chain.filter(exchange);
            }
        }
         //String token = exchange.getRequest().getQueryParams().getFirst("token");
        String token1 = getToken(exchange.getRequest());
        System.out.println(token1);
       /* if (token == null || token.isEmpty()) {
            ServerHttpResponse response = exchange.getResponse();
            // 封装错误信息
            Map<String, Object> responseData = Maps.newHashMap();
            responseData.put("code", 401);
            responseData.put("message", "非法请求");
            responseData.put("cause", "Token is empty");
            try {
                // 将信息转换为 JSON
                ObjectMapper objectMapper = new ObjectMapper();
                byte[] data = objectMapper.writeValueAsBytes(responseData);
                // 输出错误信息到页面
                DataBuffer buffer = response.bufferFactory().wrap(data);
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
                return response.writeWith(Mono.just(buffer));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }*/
        return chain.filter(exchange);
    }

    /**
     * 设置过滤器的执行顺序
     *
     * @return
     */
    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }


    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(Constants.HEADER);

        return token;
    }
}
